package sharetime.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

public class IoUtil {

	public IoUtil() {
	}

	public static void close(InputStream i) {
		if (i != null)
			try {
				i.close();
			} catch (IOException e) {
			}
	}

	public static void flushAndClose(OutputStream o) {
		if (o != null)
			try {
				o.flush();
				o.close();
			} catch (IOException e) {
			}
	}

	public static void close(OutputStream o) {
		if (o != null)
			try {
				o.close();
			} catch (IOException e) {
			}
	}

	public static void close(Reader r) {
		if (r != null)
			try {
				r.close();
			} catch (IOException e) {
			}
	}

	public static void close(Writer w) {
		if (w != null)
			try {
				w.close();
			} catch (IOException e) {
			}
	}

	public static void flushAndClose(Writer w) {
		if (w != null)
			try {
				w.flush();
				w.close();
			} catch (IOException e) {
			}
	}

	public static void copy(InputStream i, OutputStream o) throws IOException {
		try {
			FileUtils.copyStream(i, o);
		} catch (IOException e) {
			throw e;
		}
		close(i);
		close(o);
	}

	public static File createTmpDir(String prefix, String suffix)
			throws IOException {
		File f = File.createTempFile(prefix, suffix);
		f.delete();
		if (!f.mkdirs())
			throw new IOException("Failed to create a temporary directory.");
		else
			return f;
	}

	public static byte[] readInputStream(InputStream stream) throws IOException {
		byte bytes[] = new byte[stream.available()];
		stream.read(bytes);
		return bytes;
	}
}
